<template>
  <div>
    <van-search
      v-model="searchText"
      :show-action="showAction"
      placeholder="请输入搜索关键词"
      @click="OnClickSearch"
      maxlength="30"
      @search="OnSearch"
    />
    <ul v-if="searchResults.length">
      <li v-for="item in searchResults" :key="item.id">{{ item.name }}</li>
    </ul>
  </div>

  <van-image src="/indextop.png" fit="contain" />

  <van-notice-bar
    left-icon="volume-o"
    scrollable
    color="#1989fa"
    background="#ecf9ff"
  >
    请大家遵守社区规定，文明交流，共建和谐社交环境，如发现有违规信息可以点击举报，我们将进行封号处理。
    请勿在社区中发布支付二维码等信息。 温馨提示：每天上线登录可领取1积分。
  </van-notice-bar>
  <van-tabs
    v-model:active="activeName"
    animated="true"
    color="#000000"
    @click-tab="handleTabChange"
  >
    <van-tab title="全部" name="全部" />
    <van-tab title="校内活动" name="校内活动" />
    <van-tab title="打听求助" name="打听求助" />
    <van-tab title="失物招领" name="失物招领" />
    <van-tab title="表白交友" name="表白交友" />
    <van-tab title="校园美景" name="校园美景" />
    <van-tab title="校外服务" name="校外服务" />
    <van-tab title="二手交易" name="二手交易" />
    <van-tab title="校园趣事" name="校园趣事" />
  </van-tabs>
  <van-list
    class="list"
    v-model="loading"
    :finished="finished"
    loading-text="加载中..."
    finished-text="没有更多了"
    offset="10"
    @load="onLoad"
  >
    <van-back-top style="color: white" right="3vw" bottom="12vh" />
    <van-cell-group>
      <van-cell v-for="post in list" :key="post.id">
        <van-row class="van-rowstyle">
          <van-col>
            <van-image
              round
              fit="cover"
              :src="post.useravatar"
              width="2rem"
              height="2rem"
            />
          </van-col>
          <van-col offset="1">
            <van-text-ellipsis
              :class="[
                'usernamestyle',
                { 'vip-color': post.userrole === 'vip' },
              ]"
              rows="8"
              :content="post.username"
            />
          </van-col>
          <van-col offset="1">
            <van-tag
              v-if="post.userrole === 'admin'"
              plain
              type="primary"
              color="#808080"
              round
              >管理员</van-tag
            >
            <van-tag
              v-if="post.userrole === 'vip'"
              type="primary"
              color="black"
              text-color="gold"
              round
              style="font-style: italic"
              >VIP</van-tag
            >
          </van-col>
          <van-col offset="1">
            <van-tag
              v-if="post.isTop == 1"
              round
              plain
              type="primary"
              color="#808080"
              >置顶</van-tag
            >
          </van-col>
          <van-col>
            <van-popover
              v-model:show="post.showPopover"
              :actions="actions"
              @select="onSelect(post.id)"
            >
              <template #reference>... </template>
            </van-popover>
          </van-col>
        </van-row>
        <van-row class="van-rowstyle" @click="OnClickPost(post)">
          <van-col offset="3">
            <van-text-ellipsis
              class="ellstyle"
              rows="50"
              :content="post.content"
            />
          </van-col>
        </van-row>
        <van-row
          justify="space"
          @click="OnClickPost(post)"
          class="van-rowstyle"
        >
          <van-col offset="3" v-for="img in post.imagepath" :key="img">
            <van-image :src="img" fit="cover" width="6.5rem" height="6.5rem"
              ><template v-slot:error>加载失败</template></van-image
            >
          </van-col>
        </van-row>
        <van-row justify="space-between" class="van-rowstyle">
          <van-col class="tagstyle" span="6" offset="1">
            #{{ post.tag }}
          </van-col>
          <van-col span="6" offset="1">
            {{ post.createTime }}
          </van-col>
          <van-col span="6" offset="1"> {{ post.seeNum }}人围观 </van-col>
        </van-row>
      </van-cell>
    </van-cell-group>
  </van-list>

  <!--    列表        -->

  <van-tabbar @change="OnchangeTab">
    <van-tabbar-item name="" icon="wap-home-o" to="">主页</van-tabbar-item>
    <van-tabbar-item name="search" icon="search">搜索</van-tabbar-item>
    <van-tabbar-item name="putout" icon="add">发布</van-tabbar-item>
    <van-tabbar-item name="user" icon="user-o">个人中心</van-tabbar-item>
  </van-tabbar>
</template>

<script>
import router from "@/router";
import MyAxios from "@/plugins/MyAxios";
import { ref } from "vue";
import store from "@/store";
import { showToast } from "vant";
export default {
  setup() {
    const backPath = ref(store.state.backedPath);
    window.scrollTo(0, store.state.recruitScrollY);
    const showAction = ref(false);

    const activeName = ref("");
    activeName.value = store.state.storeActionName;
    const OnClickPost = (post) => {
      store.commit("changeRecruitScrollY", window.scrollY);
      router.push({
        path: "/post", // 假设你的路由路径是 /home, /about 这样的
        query: { id: post.id },
      });
    };
    const OnchangeTab = (name) => {
      store.commit("changeRecruitScrollY", window.scrollY);
      router.push({
        path: `/${name}`, // 假设你的路由路径是 /home, /about 这样的
      });
    };

    const OnClickSearch = () => {
      store.commit("changeRecruitScrollY", window.scrollY);
      router.push({
        path: "/search",
      });
    };

    /**
     * 计算时间差
     * @param timeString
     * @returns {*}
     */
    const formatTimeDifference = (timeString) => {
      const now = new Date();
      const createTime = new Date(timeString);
      const diff = now - createTime;
      let result;

      if (diff < 0) {
        result = "未来时间";
      } else if (diff < 1000 * 60) {
        // 小于1分钟
        result = `${Math.floor(diff / 1000)} 秒前`;
      } else if (diff < 1000 * 60 * 60) {
        // 小于1小时
        result = `${Math.floor(diff / (1000 * 60))} 分钟前`;
      } else if (diff < 1000 * 60 * 60 * 24) {
        // 小于1天
        result = `${Math.floor(diff / (1000 * 60 * 60))} 小时前`;
      } else {
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        result = `${days} 天前`;
      }

      return result;
    };

    const getUser = (id) => {
      const res = MyAxios.get("/user/get/vo", {
        params: {
          id: id,
        },
      });
      return res;
    };

    const list = ref([]);
    const page = ref(0); // 当前页码
    const loading = ref(false); // 是否正在加载中
    const finished = ref(false); // 是否加载完成
    const totalPages = ref(0); // 最多有多少页
    const tag = ref("");
    const onLoad = async () => {
      page.value = store.state.storePageNumber;
      list.value = store.state.storePostList;
      //tag同部
      tag.value = activeName.value;

      if (finished.value) return;
      loading.value = true; // 设置正在加载状态
      page.value = page.value + 1; // 页码加1
      store.state.storePageNumber = page.value;
      if (tag.value === "全部") tag.value = null;
      if (page.value === 1) {
        MyAxios.get("/post/getIsTopPost", { params: { tag: tag.value } }).then(
          (res) => {
            for (let i = 0; i < res.data.length; i++) {
              const {
                anon,
                anon_name,
                content,
                createTime,
                id,
                tags,
                imgpath,
                userId,
                seeNum,
              } = res.data[i];

              let useravatar = ref("");
              let username = ref("");
              let userrole = ref("");

              getUser(userId).then((res) => {
                const { userAvatar, userName, userRole } = res.data;

                if (userAvatar === null || anon === 1) {
                  useravatar.value = store.state.anonImg;
                } else {
                  useravatar.value =
                    "http://" +
                    backPath.value +
                    "/api/userimages/" +
                    userAvatar;
                }
                if (anon === 1) {
                  username.value = anon_name;
                } else {
                  username.value = userName;
                }
                if (userRole !== null) {
                  userrole.value = userRole;
                }
              });
              const arr = JSON.parse(tags);

              const tag = arr[0];

              const formattedCreateTime = formatTimeDifference(createTime);

              let imagePaths = ref([]); // 更改为更具描述性的变量名
              try {
                imagePaths.value = JSON.parse(imgpath); // 直接解析到响应式引用的value中
              } catch (error) {
                console.error("Parsing imgpath failed:", error); // 添加错误处理
              }

              if (imagePaths.value != null) {
                for (let i = 0; i < imagePaths.value.length; i++) {
                  // 使用模板字符串优化URL拼接
                  imagePaths.value[
                    i
                  ] = `http://${backPath.value}/api/postimages/${imagePaths.value[i]}`;
                }
              }

              // const createtimeFiter = createtime.match(/^\d{4}-\d{2}-\d{2}/)[0];
              list.value.push({
                anon,
                anon_name,
                content,
                createTime: formattedCreateTime,
                id,
                tag,
                seeNum,
                useravatar,
                username,
                imagepath: imagePaths.value,
                showPopover: false,
                isTop: 1,
                userrole,
              });
            }
            store.state.storePostList = list.value;
          }
        );
      }
      const response = await MyAxios.get("/post/page", {
        params: { current: page.value, size: 15, tag: tag.value },
      });
      totalPages.value = response.data.pages; // 获取总页码
      if (page.value > totalPages.value) {
        finished.value = true; // 加载完成，设置结束状态
      }
      for (let i = 0; i < response.data.records.length; i++) {
        const {
          anon,
          anon_name,
          content,
          createTime,
          id,
          tags,
          imgpath,
          userId,
          seeNum,
        } = response.data.records[i];

        let useravatar = ref("");
        let username = ref("");
        let userrole = ref("");

        getUser(userId).then((res) => {
          const { userAvatar, userName, userRole } = res.data;

          if (userAvatar === null || anon === 1) {
            useravatar.value = store.state.anonImg;
          } else {
            useravatar.value =
              "http://" + backPath.value + "/api/userimages/" + userAvatar;
          }
          if (anon === 1) {
            username.value = anon_name;
          } else {
            username.value = userName;
          }
          if (userRole !== null) {
            userrole.value = userRole;
          }
        });
        const arr = JSON.parse(tags);

        const tag = arr[0];

        const formattedCreateTime = formatTimeDifference(createTime);

        let imagePaths = ref([]); // 更改为更具描述性的变量名
        try {
          imagePaths.value = JSON.parse(imgpath); // 直接解析到响应式引用的value中
        } catch (error) {
          console.error("Parsing imgpath failed:", error); // 添加错误处理
        }

        if (imagePaths.value != null) {
          for (let i = 0; i < imagePaths.value.length; i++) {
            // 使用模板字符串优化URL拼接
            imagePaths.value[
              i
            ] = `http://${backPath.value}/api/postimages/${imagePaths.value[i]}`;
          }
        }

        // const createtimeFiter = createtime.match(/^\d{4}-\d{2}-\d{2}/)[0];
        list.value.push({
          anon,
          anon_name,
          content,
          createTime: formattedCreateTime,
          id,
          tag,
          seeNum,
          useravatar,
          username,
          imagepath: imagePaths.value,
          showPopover: false,
          isTop: 0,
          userrole,
        });
      }
      store.state.storePostList = list.value;

      loading.value = false; // 加载完成，设置回非加载状态
    };

    const handleTabChange = () => {
      // 当标签切换时，重置list和page，并触发加载
      list.value = []; // 清空列表
      store.state.storePostList = [];
      page.value = 0; // 重置页码
      store.state.storePageNumber = 0;
      totalPages.value = 0;
      store.state.storeActionName = activeName.value;
      // 假设newActive是新的标签索引，但如果您需要基于标签标题来加载数据，
      // 您可能需要先找到对应的标签标题，然后再用它来加载数据
      // 这里为了简化，我们直接调用onLoad函数，假设它知道如何处理
      // 实际上，您可能需要根据newActive的值来选择性地调用onLoad
      loading.value = true;
      finished.value = false;
      onLoad();
    };

    // 通过 actions 属性来定义菜单选项
    const actions = [{ text: "举报" }];

    const onSelect = (postid) => {
      MyAxios.post("/report/addreport", { postId: postid, userId: postid });
      showToast("举报成功");
    };

    // 搜索框相关(ES)
    const searchText = ref("");
    const searchResults = ref([]);
    const OnSearch = () => {
      MyAxios.get("/post/search", {
        params: {
          content: searchText.value,
        },
      }).then((res) => {
        searchResults.value = res.data;
      });
    };
    return {
      showAction,
      activeName,
      OnClickPost,
      OnClickSearch,
      OnchangeTab,
      list,
      page,
      loading,
      finished,
      totalPages,
      onLoad,
      handleTabChange,
      actions,
      onSelect,
      searchText,
      searchResults,
      OnSearch,
    };
  },
};
</script>

<style scoped>
.ellstyle {
  /* 调整字体大小 */
  font-size: 16px; /* 或者您想要的任何大小 */

  color: black;
  text-align: left;
  line-height: 1.6;
  /* 调整字体类型 */
  font-family: Arial, sans-serif; /* 或者您喜欢的任何字体 */
}

.usernamestyle {
  font-size: 15px;
  line-height: 1.5;
  color: #394968;
}

.vip-color {
  color: transparent;
  background: linear-gradient(to right, red, orange);
  -webkit-background-clip: text; /* 将背景裁剪为文本区域 */
  -webkit-text-fill-color: transparent; /* 设置文本填充颜色为透明 */
}

.tagstyle {
  font-size: 15px;
  color: #00388b;
}
/* 调整行之间的间距 */
.van-rowstyle {
  margin-bottom: 5px; /* 在每行下方添加间距 */
}
</style>
